import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Tab, Balloon, Menu, Dropdown, Tag, Divider, Badge } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import {
  Header,
  Body,
  BodyContent,
  OperationBar,
  Content,
  ButtonIcon,
  SearchIcon,
  YunxiaoList,
  YunxiaoIcon,
  Star,
  Title,
} from '@alife/devops-ui';
import { ENUM, ORGANIZATION_ADMIN_ROLES, PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import utils from 'utils/index';
import track, { enterPage, Perf } from 'utils/track';
import { getIntroPointState, setIntroPointState } from 'api';
import { navigate, Link } from 'utils/router';
import TextAvatar from '@txdfe/at-text-avatar';
import RepoSkeleton from 'components/skeleton/orgRepo';
import ListEmpty from 'atComponents/ListEmpty';
import MemberList from 'components/memberList';
import CreateProjectModal from 'components/createProjectModal/loadable';
import ImportProjectModal from 'components/importProjectModal/loadable';
import { access } from 'components/accessContainer/util';
import PathEllipsis from 'components/pathEllipsis';
import * as actions from '../actions/index';
import WelcomeToUseCodeupTooltipDialog from './welcomeDialog';
import debounce from 'lodash.debounce';
import KEYCODE from 'utils/keycode';
import RepoAdvancedSearch from 'components/repoAdvancedSearch';
import PremiumService from 'components/premiumService';
// import Modaldemo from './Modaldemo';
import intl from '../../../../../../../locale';
const defaultNamespaceId = utils.getUrlSearchParam('namespace_id');

const { user_role } = window.FORCE.organization;
// const PROJECT_ROLES = ['REPORTER', 'ORG_MEMBER', 'DEVELOPER', 'MASTER', 'OWNER', 'ORG_ADMIN', 'ORG_OWNER', 'ADMIN'];

const { Tooltip } = Balloon;
const trackPageEnum = {
  mine: 'Organization-Repos-Mine',
  all: 'Organization-Repos-All',
};

const { visibility_levels } = ENUM;
const { ctrlKey, ctrlTxt } = ENUM.getOSKeyMap();

class Root extends Component {
  static propTypes = {
    projects: PropTypes.arrayOf(PropTypes.object),
    currentPage: PropTypes.number,
    total: PropTypes.number,
    order_by: PropTypes.string,
    navKey: PropTypes.string,
  };

  static defaultProps = {
    projects: null,
    currentPage: 1,
    total: 0,
    order_by: 'last_activity_at',
    navKey: '',
  };

  constructor(props) {
    super(props);
    this.state = {
      membersDialogVisible: false,
      membersDialogProject: {},
      createModalShow: false,
      // 链接url中autobind参数有，则打开弹窗
      importModalShow: false,
      welcomeShow: false,
      showWelcomeDialog: false,
      premiumStatusVisible: false,
      pageSize: 10,
    };

    this.searchShowTips = null;
    this.onSearch = debounce(this.onSearch, 500);
    const personalSetting = utils.getUrlSearchParam('open_personal_setting');
    if (personalSetting) {
      window.location.href = 'https://account-devops.aliyun.com/settings/profile';
    }
  }

  componentDidMount() {
    const navKey = utils.getUrlSearchParam('navKey') || 'mine';
    this.props.setNavKey(navKey);
    const { pageSize } = this.state;
    this.props.getProjectsCounts();
    this.props.getProjects(1, ENUM.clearType.all, pageSize);
    this.props.getRepoSettingData();

    this.getIfWelcomeShow();
    enterPage(trackPageEnum[navKey], {
      sendPerf: false,
    });

    this.getIfWelcomeToUseCodeupDialogShow();
    document.addEventListener('keydown', this.handleKeyCodeEvent);
  }

  handleKeyCodeEvent = (e) => {
    // ctrl + / 进行搜索
    if (e[ctrlKey] && e.keyCode === KEYCODE.SPLIT) {
      document.querySelector('.search-ctrl>button').click();
      document.querySelector('.search-ctrl input').focus();
    }
  };

  componentDidUpdate(prevProps) {
    if (this.props.location.search !== prevProps.location.search) {
      const navKey = utils.getUrlSearchParam('navKey') || 'mine';
      this.props.setNavKey(navKey);

      const { pageSize } = this.state;
      this.props.getProjects(1, ENUM.clearType.all, pageSize);

      enterPage(trackPageEnum[navKey], {
        sendPerf: false,
      });
    }
  }

  componentWillUnmount() {
    this.props.updateData({
      search: '',
    });
    document.removeEventListener('keydown', this.handleKeyCodeEvent);
    this.searchShowTips && clearTimeout(this.searchShowTips);
  }

  pageChange = (value) => {
    const { pageSize } = this.state;
    this.props.getProjects(value, undefined, pageSize);
  };

  pageSizeChange = (pageSize) => {
    this.props.getProjects(1, undefined, pageSize);
    this.setState({
      pageSize,
    });
  };

  filterLevel = (level) => {
    let label = '';
    visibility_levels.forEach((item) => {
      if (item.value === Number(level)) {
        label = item.label;
      }
    });
    return label;
  };

  renderMirrorSync = (project) => {
    const { last_mirror_sync_record } = project;
    if (!last_mirror_sync_record) return null;
    const { sync_status } = last_mirror_sync_record;
    if (sync_status === 'READY' || sync_status === 'SYNCHRONIZING') {
      return (
        <Balloon.Tooltip
          trigger={
            <YunxiaoIcon
              className="arrows-cycle-animate"
              type="refresh-line"
              style={{ marginLeft: 10 }}
            />
          }
        >
          {intl.get({
            id: 'code-assets.projects.containers.root.DatabaseSynchronizationIsInProgress',
            defaultMessage: '仓库同步中，为保证数据一致性，暂时禁止仓库写入，请耐心等待',
          })}
        </Balloon.Tooltip>
      );
    }
    return null;
  };

  getDataSource = () => {
    const { projects, doUnStar, doStar, navKey } = this.props;

    return projects
      ? projects.map((project) => {
        return ({
          left: <TextAvatar text={project.path.toUpperCase()} image={project.avatar_url} isCover />,
          body: {
            title: (
              <span className="project-list-item-title project-list-at-path">
                <PathEllipsis
                  path={utils.getGroupPath(project.name_with_namespace)}
                  size="large"
                  extra={
                    <>
                      {project.demo_project ? (
                        <Tag className="demo-repo-tag" type="primary">
                          {intl.get({
                            id: 'code-assets.projects.containers.root.SampleCodeLibrary',
                            defaultMessage: '示例代码库',
                          })}
                        </Tag>
                      ) : null}
                      {project.archived ? (
                        <Tag className="demo-repo-tag" type="primary" color="error">
                          {intl.get({
                            id: 'code-assets.projects.containers.root.Archived',
                            defaultMessage: '已归档',
                          })}
                        </Tag>
                      ) : null}
                      {project.import_status === 'failed' ? (
                        <Tag className="demo-repo-tag" type="primary" color="warning">
                          导入失败
                        </Tag>
                      ) : null}
                      {this.renderMirrorSync(project)}
                    </>
                  }
                />
              </span>
            ),

            description: [
              <span className="project-list-item-desc">
                {project.description ? (
                  <React.Fragment>
                    <span className="project-list-item-desc-project-desc">
                      <Title trigger={<span>{project.description}</span>}>
                        <div>{project.description}</div>
                      </Title>
                    </span>
                    <span className="project-list-item-desc-divider">·</span>
                  </React.Fragment>
                ) : null}
                <span className="project-list-item-desc-time">
                  {`${intl.get({
                    id: 'code-assets.src.utils.locale.UpdatedOn',
                    defaultMessage: '更新于',
                  })} ${utils.getBeautyTime(project.last_activity_at)}`}
                </span>
              </span>,
            ],
          },

          right: {
            hoverItems: [
              (access(ORGANIZATION_ADMIN_ROLES, user_role) ||
              access(PROJECT_ADMIN_ROLES, ENUM.access_level[project.access_level])) ? (
                <Balloon.Tooltip
                  type="primary"
                  align="t"
                  trigger={
                    <ButtonIcon
                      text
                      name="add-members-line"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        this.setState({
                          membersDialogVisible: true,
                          membersDialogProject: project,
                        });
                      }}
                    />
                  }
                >
                  {intl.get({
                    id: 'code-assets.projects.containers.root.MemberManagement',
                    defaultMessage: '成员管理',
                  })}
                </Balloon.Tooltip>
              ) : null,
              (access(ORGANIZATION_ADMIN_ROLES, user_role) ||
                access(PROJECT_ADMIN_ROLES, ENUM.access_level[project.access_level])) &&
              ['none', 'finished'].includes(project.import_status) ? (
                <Balloon.Tooltip
                  type="primary"
                  align="t"
                  trigger={
                    <ButtonIcon
                      text
                      name="setting-line"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        // TODO a标签点击无效，待list组件修复
                        navigate(`/${project.path_with_namespace}/settings`);
                      }}
                    />
                  }
                >
                  {intl.get({
                    id: 'code-assets.projects.containers.root.EnableSettings',
                    defaultMessage: '打开设置',
                  })}
                </Balloon.Tooltip>
              ) : null,
              <span
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}
              >
                <Star
                  starred={project.starred}
                  onClick={() => {
                    if (project.starred) {
                      doUnStar(project.id);
                    } else {
                      doStar(project.id);
                    }
                  }}
                />
              </span>,
            ],

            items: [
              <Tag size="small">{this.filterLevel(project.visibility_level)}</Tag>,
              <span
                style={{
                  visibility: project.starred ? 'visible' : 'hidden',
                }}
              >
                <Star
                  starred={project.starred}
                  onClick={() => {
                    if (project.starred) {
                      doUnStar(project.id);
                    } else {
                      doStar(project.id);
                    }
                  }}
                  noHoverText
                />
              </span>,
            ],

            style: {
              width: 132,
              paddingLeft: 20,
            },
          },

          containerProps: {
            to: `/${project.path_with_namespace}`,
          },

          onClick: () => {
            track({
              action: 'enter_repo',
              page: trackPageEnum[navKey],
              type: project.demo_project ? 'demo-list' : 'normal-list',
            });
          },
        });
      })
      : [];
  };

  getIfWelcomeShow = () => {
    getIntroPointState('welcome_to_codeup_pop')
      .then((result) => {
        if (result.state) {
          this.setState({
            welcomeShow: result.state,
          });
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  setIfWelcomeShow = () => {
    const { navKey } = this.props;
    track({
      action: 'close_welcome_to_codeup_pop',
      page: trackPageEnum[navKey],
    });

    setIntroPointState('welcome_to_codeup_pop')
      .then(() => {
        this.setState({
          welcomeShow: false,
        });
      })
      .catch((err) => {
        console.error(err);
      });
  };

  getIfWelcomeToUseCodeupDialogShow = () => {
    getIntroPointState('welcome_to_use_codeup_pop')
      .then((result) => {
        this.props.updateData({
          welcomeDialogStatus: result.state,
        });

        if (result.state) {
          this.setState({
            showWelcomeDialog: result.state,
          });
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  onWelcomeToUseCodeupClose = () => {
    this.setState({
      showWelcomeDialog: false,
    });

    this.props.updateData({
      welcomeDialogStatus: false,
    });
  };

  renderMembersDialog = () => {
    const { membersDialogVisible: visible, membersDialogProject: project } = this.state;

    return (
      <MemberList
        visible={visible}
        pathResourceId={project.id}
        isAdmin
        parentId={project.namespace_id}
        pathResourceType="project"
        align="tr br"
        role={ENUM.access_level[project.access_level]}
        onClose={() => {
          this.setState({
            membersDialogVisible: false,
            // membersDialogProject: {},
          });
        }}
      />
    );
  };

  onChangeTab = (key) => {
    this.props.setNavKey(key.split('=')[1]);
    navigate(key);
  };

  renderContent = (dataSource) => {
    const { navKey } = this.props;
    const { Item } = YunxiaoList;

    return (
      <>
        <YunxiaoList
          className="organization-project-list"
          dataSource={dataSource}
          renderItem={(item, i) => (
            <Link to={item.containerProps.to}>
              <Item
                style={{ cursor: 'pointer' }}
                key={i}
                title={item.body.title}
                description={item.body.description}
                cover={item.left}
                extra={
                  <Item.HoverToggles align="right">
                    <Item.Actions align="right">{item.right.items}</Item.Actions>
                    {<Item.Actions align="right">{item.right.hoverItems}</Item.Actions>}
                  </Item.HoverToggles>
                }
              />
            </Link>
          )}
          onItemClick={() => {
            // navigate(item.containerProps.to);
          }}
          // pagination={{
          //   onLoadMore: (page) => {
          //     this.props.getProjects(page);
          //   },
          //   hasMore,
          //   useWindow: false,
          //   getScrollParent: () => {
          //     return document.querySelector('#container');
          //   },
          // }}
          hasHoverItems
        />

        <Perf page={trackPageEnum[navKey]} />
      </>
    );
  };

  handleSort = (keys) => {
    this.props.updateData({
      order_by: keys[0],
    });

    const { pageSize } = this.state;
    this.props.getProjects(1, ENUM.clearType.all, pageSize);
  };

  getCreateProjectAccess = () => {
    const { repoCreatorIdentity } = this.props;
    return (
      access(ORGANIZATION_ADMIN_ROLES, user_role) ||
      repoCreatorIdentity.map((item) => ENUM.access_level[item]).includes(user_role)
    );
  };

  // 搜索条件
  onSearch = (search) => {
    this.props.updateData({
      projects: [],
      currentPage: 1,
      isLoading: true,
      search,
    });
    const { pageSize } = this.state;
    this.props.getProjectsCounts();
    this.props.getProjects(1, ENUM.clearType.all, pageSize);
  };

  renderPageHeader = () => {
    const { total, order_by, archived } = this.props;
    const hasCreateProjectAccess = this.getCreateProjectAccess();
    const extra = (
      <>
        <SearchIcon
          direction="rtl"
          placeholder={intl.get({
            id: 'code-assets.projects.containers.root.SearchCodeBase',
            defaultMessage: '搜索代码库',
          })}
          onChange={(value) => {
            this.onSearch(value);
          }}
          defaultValue={this.props.search}
          triggerTooltipProps={{
            children: (
              <div>
                {intl.get({
                  id: 'code-assets.projects.containers.root.Search',
                  defaultMessage: '搜索',
                })}
                <br />
                {ctrlTxt} + /
              </div>
            ),

            align: 't',
          }}
          className="search-ctrl"
        />

        <RepoAdvancedSearch
          archived={archived}
          onSearch={(data) => {
            this.props.updateData({
              projects: [],
              currentPage: 1,
              isLoading: true,
              archived: data.archived,
            });

            this.pageChange(1);
            this.props.getProjectsCounts();
          }}
        />

        <Dropdown trigger={<ButtonIcon text name="sort-line" />} triggerType="click" align="tr br">
          <Menu onSelect={this.handleSort} selectMode="single" selectedKeys={order_by}>
            {/* <Menu.Item key="last_activity_at">我更新时间</Menu.Item> */}
            <Menu.Item key="last_activity_at">
              {intl.get({
                id: 'code-assets.projects.containers.root.UpdateTime',
                defaultMessage: '更新时间',
              })}
            </Menu.Item>
            <Menu.Item key="created_at">
              {intl.get({
                id: 'code-assets.projects.containers.root.Created',
                defaultMessage: '创建时间',
              })}
            </Menu.Item>
          </Menu>
        </Dropdown>
        {total === 0 && !this.props.search && !this.props.isLoading ? null : (
          <>
            {hasCreateProjectAccess ? (
              this.renderAddBtn()
            ) : (
              <>
                <Divider direction="ver" />
                <Balloon.Tooltip
                  trigger={
                    <Button type="primary" disabled>
                      {intl.get({
                        id: 'code-assets.projects.containers.root.AddDatabase',
                        defaultMessage: '添加库',
                      })}
                    </Button>
                  }
                  align="l"
                >
                  {intl.get({
                    id: 'code-assets.projects.containers.root.CurrentlyTheEnterpriseHasEnabled',
                    defaultMessage: '当前企业开启了创建库的权限管控，如有需要请联系企业管理员修改',
                  })}
                </Balloon.Tooltip>
              </>
            )}
          </>
        )}
      </>
    );

    return (
      <Header
        title={intl.get({
          id: 'code-assets.projects.containers.root.CodeBase',
          defaultMessage: '代码库',
        })}
        operation={extra}
      />

      // <PageHeader
      //   breadcrumb={[
      //     {
      //       text: (
      //         <span style={{ fontWeight: 'bold', fontSize: '20px' }}>
      //           代码库
      //           {/* {this.props.navKey === 'mine' ? '我参与的' : '全部'}
      //           {!isLoading ? ` · ${total}` : null} */}
      //         </span>
      //       ),
      //     },
      //   ]}
      //   // 长度为0且无搜索条件去除右顶部extra
      //   extra={extra}
      //   className={'no-mr-b page-header-height'}
      // />
    );
  };

  openNewProjectModal = (type = '') => {
    const { navKey } = this.props;
    track({
      action: 'new_repo',
      page: trackPageEnum[navKey],
      type: type === '' ? null : type,
    });

    this.setState({
      createModalShow: true,
    });
  };

  openImportProjectModal = (type = '') => {
    const { navKey } = this.props;
    track({
      action: 'import_repo',
      page: trackPageEnum[navKey],
      type: type === '' ? null : type,
    });

    this.setState({
      importModalShow: true,
    });
  };

  renderAddBtn = (type = 'primary') => {
    return (
      <>
        <Divider direction="ver" />
        <Dropdown
          trigger={
            <Button type={type} id="project-dropdown-btn">
              {intl.get({
                id: 'code-assets.projects.containers.root.AddDatabase',
                defaultMessage: '添加库',
              })}
            </Button>
          }
          safeNode={() => document.querySelector('#project-dropdown-btn')}
          triggerType="click"
          align="tr br"
        >
          <Menu>
            <Menu.Item
              onClick={() => {
                this.openNewProjectModal();
              }}
            >
              {intl.get({
                id: 'code-assets.projects.containers.root.CreateACodeLibrary',
                defaultMessage: '新建代码库',
              })}
            </Menu.Item>
            <Menu.Item
              onClick={() => {
                this.openImportProjectModal();
              }}
            >
              {intl.get({
                id: 'code-assets.projects.containers.root.ImportCodeLibrary',
                defaultMessage: '导入代码库',
              })}
            </Menu.Item>
          </Menu>
        </Dropdown>
      </>
    );
  };

  renderWelcome = () => {
    const { welcomeShow } = this.state;
    const { projects, repoCreatorIdentity } = this.props;

    if (!welcomeShow || !projects || !projects.length) {
      // 没有代码库不展示
      return null;
    }

    const allowCreateRepo = utils.allowCreateRepo(repoCreatorIdentity, user_role);
    return (
      <div className="weleome-banner">
        <div className="weleome-banner-text-container">
          <div className="weleome-banner-title">
            <span style={{ marginRight: 8 }}>👏</span>
            {intl.get({
              id: 'code-assets.projects.containers.root.WelcomeToCodeup',
              defaultMessage: '欢迎使用 Codeup',
            })}
          </div>
          <div className="weleome-banner-desc">
            {intl.get({
              id: 'code-assets.projects.containers.root.CodeupIsDesignedToEnsure',
              defaultMessage:
                'Codeup 致力于保障企业代码资产安全，支持自动化代码扫描、合并评审管控等高级功能',
            })}
          </div>
          {allowCreateRepo ? (
            <div>
              <Button
                type="normal"
                onClick={() => {
                  this.openNewProjectModal('Info Bar');
                }}
              >
                {intl.get({
                  id: 'code-assets.src.utils.locale.CreateACodeLibrary',
                  defaultMessage: '新建代码库',
                })}
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                type="normal"
                onClick={() => {
                  this.openImportProjectModal('Info Bar');
                }}
              >
                {intl.get({
                  id: 'code-assets.src.utils.locale.ImportCodeLibrary',
                  defaultMessage: '导入代码库',
                })}
              </Button>
            </div>
          ) : (
            <div>
              <Tooltip
                trigger={
                  <Button type="normal" disabled>
                    {intl.get({
                      id: 'code-assets.src.utils.locale.CreateACodeLibrary',
                      defaultMessage: '新建代码库',
                    })}
                  </Button>
                }
                align="t"
              >
                {intl.get({
                  id: 'code-assets.projects.containers.root.TheEnterpriseDoesNotAllow',
                  defaultMessage: '企业不允许当前角色创建库，如有需要请联系企业管理员修改',
                })}
              </Tooltip>

              <Tooltip
                trigger={
                  <Button type="normal" style={{ marginLeft: '10px' }} disabled>
                    {intl.get({
                      id: 'code-assets.src.utils.locale.ImportCodeLibrary',
                      defaultMessage: '导入代码库',
                    })}
                  </Button>
                }
                align="t"
              >
                {intl.get({
                  id: 'code-assets.projects.containers.root.TheEnterpriseDoesNotAllow',
                  defaultMessage: '企业不允许当前角色创建库，如有需要请联系企业管理员修改',
                })}
              </Tooltip>
            </div>
          )}
        </div>
        <Tooltip
          trigger={
            <Button
              type="secondary"
              className="weleome-banner-close-btn"
              onClick={this.setIfWelcomeShow}
            >
              <YunxiaoIcon type="false-line" />
            </Button>
          }
          align="t"
          text={intl.get({
            id: 'code-assets.projects.containers.root.NoLongerDisplayed',
            defaultMessage: '不再显示',
          })}
        />

        <img
          className="weleome-banner-bg-left"
          src="https://img.alicdn.com/tfs/TB1u9AVn.Y1gK0jSZFMXXaWcVXa-220-336.png"
        />

        <img
          className="weleome-banner-bg-right"
          src="https://img.alicdn.com/tfs/TB1jyw2n8r0gK0jSZFnXXbRRXXa-572-336.png"
        />
      </div>
    );
  };

  closeModal = (type) => {
    this.setState({
      [type]: false,
    });
  };

  renderBtns = (hasCreateProjectAccess) => {
    const btns = hasCreateProjectAccess
      ? [
        <Button
          type="primary"
          onClick={() => {
              this.openNewProjectModal();
            }}
        >
          {intl.get({
              id: 'code-assets.projects.containers.root.CreateACodeLibrary',
              defaultMessage: '新建代码库',
            })}
        </Button>,
        <Button
          type="normal"
          onClick={() => {
              this.openImportProjectModal();
            }}
        >
          {intl.get({
              id: 'code-assets.projects.containers.root.ImportCodeLibrary',
              defaultMessage: '导入代码库',
            })}
        </Button>,
        ]
      : [];
    return btns;
  };

  renderEmpty = () => {
    const { search, navKey } = this.props;
    const hasCreateProjectAccess = this.getCreateProjectAccess();
    if (search) {
      return (
        <ListEmpty
          fullPage
          type="org"
          description="抱歉，未找到匹配结果"
          className="no-btns"
          imgType="search"
        />
      );
    } else if (navKey === 'all') {
      return (
        <ListEmpty
          fullPage
          type="org"
          content="暂无可查看的代码库"
          description="立即创建代码库，开始研发协作吧"
          image="none"
          btns={this.renderBtns(hasCreateProjectAccess)}
        />
      );
    }
    return (
      <ListEmpty
        fullPage
        type="org"
        content="暂无参与的代码库"
        description="立即创建或参与代码库，开始研发协作吧"
        image="none"
        btns={this.renderBtns(hasCreateProjectAccess)}
      />
    );
  };

  render() {
    const { isLoading, repoCreatorIdentity, currentPage, total, totalMine, totalAll } = this.props;
    const { createModalShow, importModalShow, showWelcomeDialog, premiumStatusVisible } =
      this.state;
    // 根据tab 获取数据
    const dataSource = this.getDataSource();
    const auto_bind = utils.getUrlSearchParam('auto_bind') || '';
    return (
      <>
        {this.renderPageHeader()}
        <Body className="project-container-root">
          <BodyContent>
            {this.renderWelcome()}
            <OperationBar>
              <Tab
                onChange={this.onChangeTab}
                activeKey={`/?navKey=${this.props.navKey ? this.props.navKey : 'mine'}`}
                animation={false}
              >
                <Tab.Item
                  title={
                    <span className="title-span-badge">
                      <span>
                        {intl.get({
                          id: 'code-assets.projects.containers.root.IParticipatedIn',
                          defaultMessage: '我参与的',
                        })}
                      </span>
                      <Badge count={totalMine} showZero overflowCount={null} />
                    </span>
                  }
                  key="/?navKey=mine"
                />

                {user_role !== 'ORG_EXTERNAL_MEMBER' ? (
                  <Tab.Item
                    title={
                      <span className="title-span-badge">
                        <span>
                          {intl.get({
                            id: 'code-assets.projects.containers.root.All',
                            defaultMessage: '全部',
                          })}
                        </span>
                        <Badge count={totalAll} showZero overflowCount={null} />
                      </span>
                    }
                    key="/?navKey=all"
                  />
                ) : null}
              </Tab>
            </OperationBar>
            <Content>
              {!isLoading ? (
                <>{dataSource.length === 0 ? this.renderEmpty() : this.renderContent(dataSource)}</>
              ) : (
                <RepoSkeleton />
              )}
            </Content>
            <Pagination
              current={currentPage}
              total={total}
              onChange={this.pageChange}
              pageSize={this.state.pageSize}
              onPageSizeChange={this.pageSizeChange}
            />
          </BodyContent>
        </Body>

        {premiumStatusVisible && showWelcomeDialog ? (
          <WelcomeToUseCodeupTooltipDialog
            show={showWelcomeDialog}
            repoCreatorIdentity={repoCreatorIdentity}
            onClose={this.onWelcomeToUseCodeupClose}
          />
        ) : null}

        {this.renderMembersDialog()}
        {createModalShow && (
          <CreateProjectModal
            defaultNamespaceId={defaultNamespaceId}
            closeModal={() => {
              this.closeModal('createModalShow');
            }}
            isModalOpen={createModalShow}
            onCreateSuccess={() => {
              this.props.updateData({
                createRepositorySuccess: true,
              });
            }}
          />
        )}

        {(auto_bind || importModalShow) && (
          <ImportProjectModal
            defaultNamespaceId={defaultNamespaceId}
            closeModal={() => {
              this.closeModal('importModalShow');
              this.props.updateData({
                closeImportRepository: true,
              });
            }}
            isModalOpen={auto_bind || importModalShow}
          />
        )}
        <PremiumService
          premiumstatus={() => {
            this.setState({ premiumStatusVisible: true });
          }}
        />
      </>
    );
  }
}

export default connect(
  (state) => state.organization.projects,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
